const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, '邮箱不能为空'],
    unique: true,
    lowercase: true,
    trim: true,
    match: [/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/, '请输入有效的邮箱地址']
  },
  password: {
    type: String,
    required: [true, '密码不能为空'],
    minlength: [6, '密码至少6个字符']
  },
  name: {
    type: String,
    required: [true, '姓名不能为空'],
    trim: true,
    maxlength: [50, '姓名最多50个字符']
  },
  bio: {
    type: String,
    trim: true,
    maxlength: [200, '个人简介最多200个字符'],
    default: null
  },
  phone: {
    type: String,
    trim: true,
    maxlength: [20, '手机号最多20个字符'],
    default: null
  },
  location: {
      type: String,
    trim: true,
    maxlength: [100, '地区最多100个字符'],
    default: null
  },
  avatar: {
    type: String,
    trim: true,
    maxlength: [500, '头像URL最多500个字符'],
    default: null
  },
  isActive: {
    type: Boolean,
    default: true
  },
  lastLoginAt: {
    type: Date,
    default: null
  }
}, {
  timestamps: true, // 自动添加createdAt和updatedAt
  toJSON: {
    transform: function(doc, ret) {
      // 返回JSON时隐藏敏感信息
      delete ret.password;
      delete ret.__v;
      return ret;
    }
  }
});

// 密码加密中间件
userSchema.pre('save', async function(next) {
  // 只在密码被修改时才加密
  if (!this.isModified('password')) return next();
  
  try {
    // 生成盐值并加密密码
    const salt = await bcrypt.genSalt(12);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// 密码验证方法
userSchema.methods.comparePassword = async function(candidatePassword) {
  return await bcrypt.compare(candidatePassword, this.password);
};

// 静态方法：通过邮箱查找用户
userSchema.statics.findByEmailOrUsername = function(identifier) {
  return this.findOne({
    email: identifier.toLowerCase()
  });
};

// 索引优化
userSchema.index({ email: 1 });
userSchema.index({ createdAt: -1 });

module.exports = mongoose.model('User', userSchema); 